var jwt = require('jsonwebtoken') // 使用jwt签名
const config = require('../config/config')

class Interceptor {
  // 构造函数
  constructor(req) {
    this.guestAction = [
      'home/login',
      'users/register',
      'users/login',
      'users/logout'
    ]
    this.req = req
    let arr = req.url.split('/') // 解析用户请求的路径
    for (let i = 0, length = arr.length; i < length; i++) {
      // 去除 GET 请求路径上携带的参数
      arr[i] = arr[i].split('?')[0]
    }
    // 路径为类似/api/roles/menus
    this.controller = ''
    if (arr[2]) {
      this.controller = arr[2]
    }
    this.action = ''
    if (arr[3]) {
      this.action = arr[3]
    }
  }

  page() {
    let { page = 1, rows = 10 } = this.req.query
    let offset = (page - 1) * rows
    return {
      offset: parseInt(offset),
      limit: parseInt(rows)
    }
  }

  totalPageCount(total) {
    let { rows = 10 } = this.req.query
    return Math.ceil(total / rows)
  }

  auth() {
    let ret = {
      code: 401,
      msg: ''
    }
    if (this.controller) {
      if (this.guestAction.indexOf(this.controller + '/' + this.action) === -1) {
        // 登录拦截
        let token = this.req.body.token || this.req.query.token || this.req.headers['x-access-token']
        if (token) {
          // 解码 token (验证 secret 和检查有效期（exp）)
          jwt.verify(token, config.jwt.secret, function(err, decoded) {
            if (err) {
              ret = {
                code: 405,
                msg: '无效的token'
              }
            } else {
              // 如果认证通过，在req中写入解密结果
              // console.log(decoded)
              ret = {
                code: 0,
                msg: '',
                authDecoded: decoded
              }
            }
          })
        } else {
          // 没有拿到token 返回错误
          ret = {
            code: 401,
            msg: '没有找到token',
            authDecoded: ''
          }
        }
      } else {
        // 无需认证的路径
        ret = {
          code: 0,
          msg: '无需认证的路径'
        }
      }
    } else {
      ret = {
        code: 404,
        msg: '没有找到对应的route'
      }
    }
    return ret
  }
}
module.exports = Interceptor
